package basicBlock;

import TAProgram.TACode;

import java.util.ArrayList;
import java.util.Iterator;

public class BasicBlock {
    String name;
    TACode head; //首指令
    ArrayList<TACode> others; //4-9

    ArrayList<BasicBlock> nextBlocks;

    public BasicBlock(String name,TACode head, ArrayList<TACode> others) {
        this.name = name;
        this.head = head;
        if(others != null) this.others = others;
        else this.others = null;
        this.nextBlocks = new ArrayList<BasicBlock>();
    }

    public BasicBlock() {
    }

    public void keepAlive(){
        Iterator<TACode> iterator = others.iterator();
        while (iterator.hasNext()){
            TACode taCode = iterator.next();
            if (taCode.getActive() == false){
                others.remove(taCode);
            }
        }
    }

    public static BasicBlock createBasicBlock(String name,TACode head, ArrayList<TACode> others,BasicBlock father){
        BasicBlock basicBlock = new BasicBlock();
        basicBlock.name = name;
        basicBlock.head = head;
        basicBlock.others = others;
        if(father != null){
            father.nextBlocks.add(basicBlock);
        }
        return basicBlock;
    }

    @Override
    public String toString() {
        String code = "";
        if(this.head != null) code += this.head.toString().equals("") ? this.head.toString() : this.head.toString()  + "\n";
        if(this.others != null){
            for (TACode other : this.others){
                code += other.toString().equals("") ? other.toString() : other.toString()  + "\n";
            }
        }
        return code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public TACode getHead() {
        return head;
    }

    public void setHead(TACode head) {
        this.head = head;
    }

    public ArrayList<TACode> getOthers() {
        return others;
    }

    public void setOthers(ArrayList<TACode> others) {
        this.others = others;
    }

    public ArrayList<BasicBlock> getNextBlocks() {
        return nextBlocks;
    }

    public void setNextBlocks(ArrayList<BasicBlock> nextBlocks) {
        this.nextBlocks = nextBlocks;
    }

    public void link(BasicBlock nextBlock) {
        this.nextBlocks.add(nextBlock);
    }
}

//1  2  3
//3 -> 2
//3 -> 1
//3 -> 3
//otherBlocks[2,1,3]